package com.desktop.android.launch

import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.desktop.android.LauncherActivity
import com.desktop.android.R
import com.desktop.android.data.AppInfo
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.*

class Launcher3Activity : AppCompatActivity() {
    private lateinit var viewPager: ViewPager2
    private lateinit var pageIndicator: LinearLayout
    private lateinit var dockRecycler: RecyclerView

    // 应用数据列表
    private var allApps = listOf<AppInfo>()

    // 分页数据
    private var pages = mutableListOf<List<AppInfo>>()

    // Dock栏应用
    private var dockApps = listOf<AppInfo>()

    // 每页显示的应用数量 (4x4网格)
    private val APPS_PER_PAGE = 16

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_launch3)

        // 初始化视图
        viewPager = findViewById(R.id.desktop_viewpager)
        pageIndicator = findViewById(R.id.page_indicator)
        dockRecycler = findViewById(R.id.dock_recycler)

        // 加载应用数据
        loadAppData()

        // 设置ViewPager页面变化监听
        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                updatePageIndicator(position)
            }
        })
    }

    /**
     * 加载设备上的应用数据
     */
    private fun loadAppData() {
        CoroutineScope(Dispatchers.IO).launch {
            // 从PackageManager获取所有已安装应用
            val packageManager = packageManager
            val apps = packageManager.getInstalledApplications(PackageManager.GET_META_DATA)
                .filter { it.flags and ApplicationInfo.FLAG_SYSTEM == 0 } // 过滤系统应用
                .sortedBy { it.loadLabel(packageManager).toString() } // 按名称排序
                .mapIndexed { index, appInfo ->
                    AppInfo(
                        packageName = appInfo.packageName,
                        appName = appInfo.loadLabel(packageManager).toString(),
                        icon = appInfo.loadIcon(packageManager),
                        position = index % APPS_PER_PAGE,
                        page = index / APPS_PER_PAGE, iconRes = 0
                    )
                }

            allApps = apps

            // 分页处理
            pages.clear()
            val pageCount = (apps.size + APPS_PER_PAGE - 1) / APPS_PER_PAGE
            for (i in 0 until pageCount) {
                val start = i * APPS_PER_PAGE
                var end = start + APPS_PER_PAGE
                if (end > apps.size) end = apps.size
                pages.add(apps.subList(start, end))
            }

            // 选择前5个应用作为Dock栏应用
            dockApps = if (apps.size >= 5) apps.subList(0, 5) else apps

            // 在主线程更新UI
            withContext(Dispatchers.Main) {
                setupViewPager()
                setupDock()
                setupPageIndicator()
                updatePageIndicator(0)
            }
        }
    }

    /**
     * 设置ViewPager
     */
    private fun setupViewPager() {
        // 创建拖拽回调
        val itemTouchHelper = ItemTouchHelperCallback(
            onItemMove = { fromPosition, toPosition ->
                moveAppItem(fromPosition, toPosition)
                true
            },
            onDragStart = {
                // 拖拽开始时的操作，如隐藏状态栏等
            },
            onDragEnd = {
                // 拖拽结束时的操作
            }
        )

        // 设置适配器
        viewPager.adapter = DesktopPagerAdapter(
            pages = pages,
            onItemClick = { appInfo ->
                // 点击应用图标，启动应用
                launchApp(appInfo)
            },
            onItemLongClick = { view, appInfo ->
                // 长按应用图标，开始拖拽
                true
            },
            itemTouchHelper = itemTouchHelper
        )
    }

    /**
     * 设置Dock栏
     */
    private fun setupDock() {
        dockRecycler.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        dockRecycler.adapter = AppGridAdapter(
            onItemClick = { appInfo ->
                launchApp(appInfo)
            },
            onItemLongClick = { view, appInfo ->
                // Dock栏图标长按也可以拖拽
                true
            }
        ).apply {
            submitList(dockApps)
        }
    }

    /**
     * 设置页面指示器
     */
    private fun setupPageIndicator() {
        pageIndicator.removeAllViews()
        val density = resources.displayMetrics.density

        for (i in pages.indices) {
            val indicator = ImageView(this).apply {
                layoutParams = ViewGroup.LayoutParams(
                    (6 * density).toInt(),
                    (6 * density).toInt()
                )
                setPadding((2 * density).toInt(), 0, (2 * density).toInt(), 0)
                setImageResource(R.drawable.tab_indicator_inactive)
            }
            pageIndicator.addView(indicator)
        }
    }

    /**
     * 更新页面指示器状态
     */
    private fun updatePageIndicator(selectedPage: Int) {
        for (i in pages.indices) {
            val indicator = pageIndicator.getChildAt(i) as ImageView
            if (i == selectedPage) {
                indicator.setImageResource(R.drawable.tab_indicator_active)
            } else {
                indicator.setImageResource(R.drawable.tab_indicator_inactive)
            }
        }
    }

    /**
     * 移动应用图标位置
     */
    private fun moveAppItem(fromPosition: Int, toPosition: Int) {
        val currentPage = viewPager.currentItem
        if (currentPage < 0 || currentPage >= pages.size) return

        // 复制当前页面的应用列表
        val currentApps = pages[currentPage].toMutableList()

        // 交换位置
        Collections.swap(currentApps, fromPosition, toPosition)

        // 更新分页数据
        pages[currentPage] = currentApps

        // 更新全局应用列表
        updateAllAppsList()

        // 通知适配器更新
        (viewPager.adapter as DesktopPagerAdapter).notifyItemChanged(currentPage)
    }

    /**
     * 更新全局应用列表
     */
    private fun updateAllAppsList() {
        allApps = pages.flatMap { it }
    }

    /**
     * 启动应用
     */
    private fun launchApp(appInfo: AppInfo) {
        try {
            val intent = packageManager.getLaunchIntentForPackage(appInfo.packageName)
            if (intent != null) {
                startActivity(intent)
            } else {
                Toast.makeText(this, "无法启动应用", Toast.LENGTH_SHORT).show()
            }
        } catch (e: Exception) {
            Toast.makeText(this, "启动应用失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
}